using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using C4F.DevKit.Bluetooth.ObjectPushProfile;
using C4F.DevKit.Bluetooth.ServiceAndDeviceDiscovery;
using System.Net.Sockets;
using System.IO;

namespace ObjectPushProfileApplication
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        List<Device> devList = null;
        RemoteService OPPService = null;
        NetworkStream networkStream = null;
        List<RemoteService> OPPServiceList;
        bool isAsync = true;

        private void btnDiscover_Click(object sender, EventArgs e)
        {
            cmbDevice.Items.Clear();
            cmbServices.Items.Clear();
            cmbDevice.Text = "";
            cmbServices.Text = "";
            cmbServices.Enabled = false;
            btnConnect.Enabled = false;
            this.Cursor = Cursors.WaitCursor;
            devList = deviceServicesManager1.DiscoverAllDevices();
            if (devList.Count != 0)
            {
                foreach (Device dev in devList)
                    cmbDevice.Items.Add(dev.Name);
            }
            if (devList.Count > 0)
            {
                cmbServices.Enabled = true;

            }
            btnOperation.Enabled = false;
            this.Cursor = Cursors.Default;

        }

        private void cmbServices_Enter(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            cmbServices.Items.Clear();
            if (devList != null && devList.Count != 0)
            {
                foreach (Device dev in devList)
                {
                    if (dev.Name == cmbDevice.Text)
                    {
                        OPPServiceList =
                            deviceServicesManager1.DiscoverServicesByType(dev, ServiceType.OBEXObjectPush);
                        if (OPPServiceList != null && OPPServiceList.Count != 0)
                        {
                            foreach (RemoteService remServ in OPPServiceList)
                            {
                                cmbServices.Items.Add(remServ.Name);
                            }
                        }
                        break;
                    }
                }
            }
            if (cmbServices.Items.Count > 0)
                btnConnect.Enabled = true;
            btnOperation.Enabled = false;
            this.Cursor = Cursors.Default;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            try
            {
                this.Cursor = Cursors.WaitCursor;
                foreach (RemoteService rem in OPPServiceList)
                {
                    if (cmbServices.Text == rem.Name)
                    {
                        OPPService = rem;
                        networkStream = OPPService.Connect();
                        btnConnect.Enabled = false;
                        cmbServices.Enabled = false;
                        oppManager1.NetworkStream = networkStream;
                        oppManager1.Connect();
                        oppManager1.ObjectPushCompleted += new BluetoothOPPManager.ObjectPushCompletedEventHandler(oppManager1_ObjectPushCompleted);
                        oppManager1.BusinessCardExchangeCompleted += new BluetoothOPPManager.BusinessCardExchangeCompletedEventHandler(oppManager1_BusinessCardExchangeCompleted);
                        oppManager1.BusinessCardPullCompleted += new BluetoothOPPManager.BusinessCardPullCompletedEventHandler(oppManager1_BusinessCardPullCompleted);
                        btnOperation.Enabled = true;
                        break;
                    }
                }
            }
            catch (ServiceConnectionException servEx)
            {
                btnConnect.Enabled = true;
                cmbServices.Enabled = true;
                MessageBox.Show(servEx.Message, "Object Push Profile", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                btnConnect.Enabled = true;
                cmbServices.Enabled = true;
                MessageBox.Show(ex.Message, "Object Push Profile", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            this.Cursor = Cursors.Default;
        }

        void oppManager1_BusinessCardPullCompleted(object sender, BusinessCardPullCompletedEventArgs e)
        {
            if (isAsync)
            {
                if (e.Error == null)
                {
                    string cardName = txtOutputFolder.Text + "\\" + e.RemoteCardName;
                    int i = 1;
                    if (File.Exists(cardName))
                    {
                        string extension = cardName.Substring(cardName.LastIndexOf(".") + 1);
                        cardName = cardName.Remove(cardName.LastIndexOf("."));
                        while (File.Exists(cardName + " (" + i + ")" + "." + extension))
                        {
                            i++;
                        }
                        cardName = cardName + " (" + i + ")" + "." + extension;
                    }
                    File.WriteAllBytes(cardName, e.RemoteCardContents);
                    MessageBox.Show("Business Card Pull Complete. " + Environment.NewLine +
                        "Received File: " + cardName,
                        "Object Push Profile", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    string errorMsg = e.Error.Message;
                    if (e.Error.InnerException != null)
                        errorMsg += Environment.NewLine + "Error Details: " + e.Error.InnerException.Message;
                    MessageBox.Show(errorMsg, "Object Push Profile", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else isAsync = true;
        }

        void oppManager1_BusinessCardExchangeCompleted(object sender, BusinessCardExchangeCompletedEventArgs e)
        {
            if (isAsync)
            {
                if (e.Error == null)
                {
                    string cardName = txtOutputFolder.Text + "\\" + e.OutputCardName;
                    int i = 1;
                    if (File.Exists(cardName))
                    {
                        string extension = cardName.Substring(cardName.LastIndexOf(".") + 1);
                        cardName = cardName.Remove(cardName.LastIndexOf("."));
                        while (File.Exists(cardName + " (" + i + ")" + "." + extension))
                        {
                            i++;
                        }
                        cardName = cardName + " (" + i + ")" + "." + extension;
                    }
                    File.WriteAllBytes(cardName, e.RemoteCardContents);

                    MessageBox.Show("Business Card Exchange Complete. " + Environment.NewLine +
                        "File Sent: " + e.LocalCardName + Environment.NewLine +
                        "Received File: " + cardName,
                        "Object Push Profile", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    string errorMsg = e.Error.Message;
                    if (e.Error.InnerException != null)
                        errorMsg += Environment.NewLine + "Error Details: " + e.Error.InnerException.Message;
                    errorMsg += Environment.NewLine + "Input File: " + e.LocalCardName;
                    MessageBox.Show(errorMsg, "Object Push Profile", MessageBoxButtons.OK, MessageBoxIcon.Error);
                
                }                   
            }
            else isAsync = true;
        }

        void oppManager1_ObjectPushCompleted(object sender, ObjectPushCompletedEventArgs e)
        {
            if (isAsync)
            {
                if (e.Error == null)
                    MessageBox.Show("Object push completed. " + Environment.NewLine +
                        "File Sent: " + e.LocalObjectName,
                        "Object Push Profile", MessageBoxButtons.OK, MessageBoxIcon.Information);
                else
                {
                    string errorMsg = e.Error.Message;
                    if (e.Error.InnerException != null)
                        errorMsg += Environment.NewLine + "Error Details: " + e.Error.InnerException.Message;
                    errorMsg += Environment.NewLine + "Input File: " + e.LocalObjectName;
                    MessageBox.Show(errorMsg, "Object Push Profile", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else isAsync = true;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            btnConnect.Enabled = false;
            cmbServices.Enabled = false;
            txtOutputFolder.Text = Environment.CurrentDirectory;
            devList = deviceServicesManager1.DiscoverAllDevices();
            if (devList.Count != 0)
            {
                foreach (Device dev in devList)
                    cmbDevice.Items.Add(dev.Name);
            }
            if (devList.Count > 0)
                cmbServices.Enabled = true;
            btnOperation.Enabled = false;
            this.Cursor = Cursors.Default;
        }

        private void btnOperation_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            switch (cmbOperation.Text)
            {
                case "Push File":
                    openFileDialog1.Filter = "All files (*.*)|*.*";
                    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        if (!string.IsNullOrEmpty(openFileDialog1.FileName))
                        {
                            try
                            {
                                if (rbSync.Checked)
                                {
                                    isAsync = false;
                                    oppManager1.PushObject(openFileDialog1.FileName);
                                    MessageBox.Show("Object push completed. " + Environment.NewLine +
                                        "File Sent: " +
                                        openFileDialog1.FileName.Substring(openFileDialog1.FileName.LastIndexOf("\\") + 1),
                                        "Object Push Profile", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                                else
                                    oppManager1.PushObjectAsync(openFileDialog1.FileName, null);
                            }
                            catch (Exception ex)
                            {
                                string errorMsg = ex.Message;
                                if (ex.InnerException != null)
                                    errorMsg += Environment.NewLine + "Error Details: " + ex.InnerException.Message;
                                errorMsg += Environment.NewLine + "Input File: " +
                                   openFileDialog1.FileName.Substring(openFileDialog1.FileName.LastIndexOf("\\") + 1);
                                MessageBox.Show(errorMsg, "Object Push Profile", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                    break;

                case "Pull Business Card":
                    try
                    {
                        if (rbSync.Checked)
                        {
                            isAsync = false;
                            string cardName;
                            byte[] card;
                            oppManager1.PullBusinessCard(out cardName, out card);
                            cardName = txtOutputFolder.Text + "\\" + cardName;
                            int i = 1;
                            if (File.Exists(cardName))
                            {
                                string extension = cardName.Substring(cardName.LastIndexOf(".") + 1);
                                cardName = cardName.Remove(cardName.LastIndexOf("."));
                                while (File.Exists(cardName + " (" + i + ")" + "." + extension))
                                {
                                    i++;
                                }
                                cardName = cardName + " (" + i + ")" + "." + extension;
                            }
                            File.WriteAllBytes(cardName, card);

                            MessageBox.Show("Business Card Pull Complete. " + Environment.NewLine +
                                "Received File: " + cardName,
                                "Object Push Profile", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        else
                            oppManager1.PullBusinessCardAsync(null);
                    }

                    catch (Exception ex)
                    {
                        string errorMsg = ex.Message;
                        if (ex.InnerException != null)
                            errorMsg += Environment.NewLine + "Error Details: " + ex.InnerException.Message;
                        MessageBox.Show(errorMsg, "Object Push Profile", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    break;

                case "Exchange Business Card":
                    openFileDialog1.Filter = "vcf files (*.vcf)|*.vcf";
                    if (openFileDialog1.ShowDialog() == DialogResult.OK)
                    {
                        if (!string.IsNullOrEmpty(openFileDialog1.FileName))
                        {
                            try
                            {
                                if (rbSync.Checked)
                                {
                                    isAsync = false;
                                    string cardName;
                                    byte[] card;
                                    oppManager1.ExchangeBusinessCards(openFileDialog1.FileName, out cardName, out card);

                                    cardName = txtOutputFolder.Text + "\\" + cardName;
                                    int i = 1;
                                    if (File.Exists(cardName))
                                    {
                                        string extension = cardName.Substring(cardName.LastIndexOf(".") + 1);
                                        cardName = cardName.Remove(cardName.LastIndexOf("."));
                                        while (File.Exists(cardName + " (" + i + ")" + "." + extension))
                                        {
                                            i++;
                                        }
                                        cardName = cardName + " (" + i + ")" + "." + extension;
                                    }
                                    File.WriteAllBytes(cardName, card);

                                    MessageBox.Show("Business Card Exchange Complete. " + Environment.NewLine +
                                        "File Sent: " +
                                        openFileDialog1.FileName.Substring(openFileDialog1.FileName.LastIndexOf("\\"))
                                        + Environment.NewLine + "Received File: " + cardName,
                                        "Object Push Profile", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                }
                                else
                                    oppManager1.ExchangeBusinessCardsAsync(openFileDialog1.FileName, null);
                            }
                            catch (Exception ex)
                            {
                                string errorMsg = ex.Message;
                                if (ex.InnerException != null)
                                    errorMsg += Environment.NewLine + "Error Details: " + ex.InnerException.Message;
                                errorMsg += Environment.NewLine + "Input File: " +
                                   openFileDialog1.FileName.Substring(openFileDialog1.FileName.LastIndexOf("\\") + 1);
                                MessageBox.Show(errorMsg, "Object Push Profile", MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }
                        }
                    }
                    break;
            }
            this.Cursor = Cursors.Default;
        }

        private void btnChangeOutputFolder_Click(object sender, EventArgs e)
        {
            if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
            {
                if (!string.IsNullOrEmpty(folderBrowserDialog1.SelectedPath))
                    txtOutputFolder.Text = folderBrowserDialog1.SelectedPath;
                else
                    txtOutputFolder.Text = Environment.CurrentDirectory;
            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Disconnect();
            this.Close();
        }

        private void Disconnect()
        {
            try
            {
                if(oppManager1.NetworkStream !=null)
                oppManager1.Disconnect();
            }
            catch (Exception ex)
            {
                btnConnect.Enabled = true;
                cmbServices.Enabled = true;
                MessageBox.Show(ex.Message, "Object Push Profile", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            try
            {
                if (OPPService != null)
                OPPService.Disconnect();
            }
            catch (Exception ex)
            {
                btnConnect.Enabled = true;
                cmbServices.Enabled = true;
                MessageBox.Show(ex.Message, "Object Push Profile", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void cmbDevice_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;
            Disconnect();
            cmbServices.Items.Clear();
            cmbServices.Text = "";
            cmbServices.Enabled = true;
            btnConnect.Enabled = false;
            btnOperation.Enabled = false;
            this.Cursor = Cursors.Default;
        }
    }
}